﻿using CustomCommon;
using jczUserService.Handlers;
using Nancy;
using Nancy.Authentication.Forms;
using Nancy.ModelBinding;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UserService.Business;
using UserService.Entity;

namespace jczUserService.Modules
{
    public class LoginModule : NancyModule
    {
        public LoginModule()
        {
            Get["/login/{genre}"] = x =>
            {
                var revalue = new
                {
                    cid = x.genre
                };
                return View["Login", revalue];
            };
            Get["/login"] = x =>
            {
                var revalue = new
                {
                    cid = "jczgroup_client"
                };
                return View["Login", revalue];
            };
            Post["/login"] = PostLogin;
            Post["/reguser"] = x =>
            {
                var logonModel = this.Bind<User>();
                bool b_add = false;
                using (UserBusiness _repo = new UserBusiness())
                {
                    b_add = _repo.InstertUser(logonModel);
                }
                if (b_add)
                {
                    var revalue = new
                    {
                        code = "200",
                        reMessage = "用户注册成功！"
                    };
                    return Response.AsJson(revalue);
                }
                else
                {
                    var revalue = new
                    {
                        code = "200",
                        reMessage = "用户注册失败！"
                    };
                    return Response.AsJson(revalue);
                }
                    
            };
        }

        public dynamic PostLogin(dynamic loginInfo)
        {
            var logonModel = this.Bind<User>();
            string client_id = this.Request.Form["client_id"];
            string jwt = "";
            User user = null;
            var revalue = new
            {
                cid = client_id
            };
            using (UserBusiness _repo = new UserBusiness())
            {
                user = _repo.FindUser(logonModel.UserName, logonModel.PasswordHash);

                if (user == null)
                {
                    //context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return View["Login", revalue];
                }
                else
                {
                    Client obj = null;
                    using (ClientBusiness _Client_repo = new ClientBusiness())
                    {
                        obj = _Client_repo.FindClient(client_id);
                    }
                    if(obj == null)
                    {
                        return View["Login", revalue];
                    }
                    else
                    {
                        string sessionId = "bhqgis-" + Guid.NewGuid().ToString();//作为Memcache的key
                        jwt = JwtAuthenticationMessageHandler.CreateJWT(user.ToClaimsIdentity());
                        MemcacheHelper.Set(sessionId, jwt, DateTime.Now.AddMinutes(20));//使用Memcache代替Session解决数据在不同Web服务器之间共享的问题。
                        System.Diagnostics.Debug.WriteLine("loginModule---CreateJWT-------------" + jwt);
                        this.Context.Request.Session["UserToken"] = jwt;
                        return Response.AsRedirect(obj.client_url+"?uid="+ sessionId);
                    }
                    
                    //Session["logintoken"] = jwt;
                }
            }
            //this.Context.Response.WithCookie("UserToken",jwt);
            //this.Context.Request.Cookies["UserToken"] = jwt;
            
            
            //var redirectUrl = string.IsNullOrWhiteSpace(logonModel.ReturnUrl) ? "/" : logonModel.ReturnUrl;
            //return this.LoginAndRedirect(Guid.Parse(user.Id), fallbackRedirectUrl: "/index");
            /*return RedirectToModule<IndexModule>()
                 .WithFormsValue("username", model.UserName)
                 .WithFormsValue("password", model.Password);*/
        }
    }
}
